package com.meilai.project.service.business.customer.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.business.customer.CustomerFollowTmpDTO;
import com.meilai.project.dto.business.customer.CustomerInfoDTO;
import com.meilai.project.dto.business.customer.CustomerInfoFlowDTO;
import com.meilai.project.dto.workflow.FlowBusinessDataSuperEntity;
import com.meilai.project.dto.workflow.WorkFlowCheckDTO;
import com.meilai.project.entity.business.customer.*;
import com.meilai.project.entity.system.Dictionary;
import com.meilai.project.entity.system.User;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.business.customer.CustomerInfoFlowMapper;
import com.meilai.project.service.business.customer.*;
import com.meilai.project.service.business.dataLevel.DataQueryBusinessLevelService;
import com.meilai.project.service.system.DictionaryService;
import com.meilai.project.service.system.UserService;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.util.WorkFlowUtil;
import com.meilai.project.vo.business.customer.CustomerChangeVO;
import com.meilai.project.vo.business.customer.CustomerFlowVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-01-06
 */
@Service
public class CustomerInfoFlowImpl extends ServiceImpl<CustomerInfoFlowMapper, CustomerInfoFlow> implements CustomerInfoFlowService {

    @Autowired
    private CustomerFollowTmpService customerFollowTmpService;

    @Autowired
    private CustomerFunnelTmpService customerFunnelTmpService;

    @Autowired
    private CustomerSelectionReasonTmpService customerSelectionReasonTmpService;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Autowired
    private CustomerFollowService customerFollowService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private CustomerPutStorageTmpService customerPutStorageTmpService;
    @Autowired
    private CustomerContactTmpService customerContactTmpService;
    @Autowired
    private CustomerContactService customerContactService;
    @Autowired
    private CustomerPutStorageService customerPutStorageService;

    @Autowired
    private DataQueryBusinessLevelService dataQueryBusinessLevelService;

    @Autowired
    private CustomerFollowAdvanceTmpService customerFollowAdvanceTmpService;

    @Autowired
    private CustomerFollowPhotoTmpService customerFollowPhotoTmpService;

    @Autowired
    private CustomerRecommendedResourcesTmpService customerRecommendedResourcesTmpService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(CustomerInfoFlowDTO dto, Boolean tmp, Long wfData_id) {
        if (!tmp) {
            Boolean flow = customerInfoService.queryCustomerFlow(dto.getCustomer_id());
            if (!flow) {
                throw new CommonException("此客户有审核信息在流程中");
            }
        }
        CustomerInfoFlow customerFollow = new CustomerInfoFlow();
        Long userId = ThreadLocalUserUtil.get().getId();
        Long main_department_id = ThreadLocalUserUtil.get().getMain_department_id();
        FlowBusinessDataSuperEntity superEntity = WorkFlowUtil.getStartSuperDataEntity(userId, main_department_id, 4, dto.getName() + "客户报备审核");
        BeanUtils.copyProperties(dto, customerFollow);
        BeanUtils.copyProperties(superEntity, customerFollow);
        customerFollow.setId(dto.getId());

        // 补全负责人姓名、电话
        if(StringUtils.isBlank(customerFollow.getPerson_in_charge_name()) && customerFollow.getPerson_in_charge_id() != null){
            User user = userService.getById(customerFollow.getPerson_in_charge_id());
            if(user != null) {
                customerFollow.setPerson_in_charge_name(user.getName());
                if(StringUtils.isBlank(customerFollow.getPerson_in_charge_phone())) customerFollow.setPerson_in_charge_phone(user.getMobile());
            }
        }

        int level = dataQueryBusinessLevelService.getUserMaxLevel("customer_contact", userId);
        boolean flag = this.saveOrUpdate(customerFollow);
        int i = 0;
        if (dto.getId() == null && tmp) {
            i = new WorkFlowUtil<CustomerInfoFlow, CustomerInfoFlowMapper>(customerFollow.getId(), userId, CustomerInfoFlow.class).SaveDraft(wfData_id != null ? wfData_id : -1L);
        } else {
            i = 1;
        }
        if (!tmp) {
            dto.setId(customerFollow.getId());
        }
        customerFunnelTmpService.remove(Wrappers.<CustomerFunnelTmp>lambdaQuery().eq(CustomerFunnelTmp::getCustomer_info_flow_id, customerFollow.getId()));
        customerSelectionReasonTmpService.remove(Wrappers.<CustomerSelectionReasonTmp>lambdaQuery().eq(CustomerSelectionReasonTmp::getCustomer_info_flow_id, customerFollow.getId()));
        customerContactTmpService.remove(Wrappers.<CustomerContactTmp>lambdaQuery().eq(CustomerContactTmp::getCustomer_info_flow_id, customerFollow.getId()));
        customerPutStorageTmpService.remove(Wrappers.<CustomerPutStorageTmp>lambdaQuery().eq(CustomerPutStorageTmp::getCustomer_info_flow_id, customerFollow.getId()));
        customerFollowTmpService.saveBatch(dto.getFollows(), customerFollow.getId());
        customerFunnelTmpService.saveBatch(dto.getFunnels().stream().map(item -> {
            CustomerFunnelTmp customerFunnelTmp = new CustomerFunnelTmp();
            customerFunnelTmp.setFunnel_type_id(item);
            customerFunnelTmp.setCustomer_info_flow_id(customerFollow.getId());
            return customerFunnelTmp;
        }).collect(Collectors.toList()));
        customerSelectionReasonTmpService.saveBatch(dto.getSelection_reasons().stream().map(item -> {
            CustomerSelectionReasonTmp customerSelectionReasonTmp = new CustomerSelectionReasonTmp();
            customerSelectionReasonTmp.setCustomer_info_flow_id(customerFollow.getId());
            customerSelectionReasonTmp.setSelection_reason_id(item);
            return customerSelectionReasonTmp;
        }).collect(Collectors.toList()));
        customerPutStorageTmpService.saveBatch(dto.getPutStorageList().stream().map(item -> {
            CustomerPutStorageTmp customerPutStorageTmp = new CustomerPutStorageTmp();
            BeanUtils.copyProperties(item, customerPutStorageTmp);
            customerPutStorageTmp.setId(null);
            customerPutStorageTmp.setCustomer_info_flow_id(customerFollow.getId());
            return customerPutStorageTmp;
        }).collect(Collectors.toList()));
        customerContactTmpService.saveBatch(dto.getContactsList().stream().map(item -> {
            CustomerContactTmp customerContactTmp = new CustomerContactTmp();
            BeanUtils.copyProperties(item, customerContactTmp);
            if (customerContactTmp.getLevel_num() == null) {
                customerContactTmp.setLevel_num(level);
            }
            customerContactTmp.setId(null);
            customerContactTmp.setCustomer_info_flow_id(customerFollow.getId());
            return customerContactTmp;
        }).collect(Collectors.toList()));
        return i == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAndStartFlow(CustomerInfoFlowDTO dto, Long wfData_id) {
        // 当前人
        Long userId = ThreadLocalUserUtil.get().getId();

        CustomerInfoFlow flow = new CustomerInfoFlow();
        BeanUtils.copyProperties(dto, flow);
        return this.save(dto, false, null) && new WorkFlowUtil<CustomerInfoFlow, CustomerInfoFlowMapper>(dto.getId(), userId, CustomerInfoFlow.class).Begin(wfData_id != null ? wfData_id : 0L, "", flow) == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean check(CustomerInfoFlowDTO dto, Boolean isCover, Boolean isReturn, String opinion) {
        Long userId = ThreadLocalUserUtil.get().getId();
        Long curCheckIndex = WorkFlowUtil.getCurCheckIndex(dto.getFlow_json(), dto.getFlow_current_node_id());
        int flowResult = -1;
        if (isReturn) {
            flowResult = new WorkFlowUtil<CustomerInfoFlow, CustomerInfoFlowMapper>(dto.getId(), userId, CustomerInfoFlow.class).ReturnBack(new WorkFlowCheckDTO(dto.getFlow_current_node_id(), curCheckIndex, opinion, ""));
        } else {
            flowResult = new WorkFlowUtil<CustomerInfoFlow, CustomerInfoFlowMapper>(dto.getId(), userId, CustomerInfoFlow.class).ToNext(new WorkFlowCheckDTO(dto.getFlow_current_node_id(), curCheckIndex, opinion, ""));
        }
        if (flowResult == 2) {
            if (isCover) {
                boolean f = customerInfoService.saveOrUpdate(dto);
                if (f) {
                    customerPutStorageService.remove(Wrappers.<CustomerPutStorage>lambdaQuery().eq(CustomerPutStorage::getCustomer_id, dto.getCustomer_id()));
                    customerContactService.remove(Wrappers.<CustomerContact>lambdaQuery().eq(CustomerContact::getCustomer_id, dto.getCustomer_id()));
                }
                this.update(Wrappers.<CustomerInfoFlow>lambdaUpdate().set(CustomerInfoFlow::getCustomer_id, dto.getCustomer_id()).eq(CustomerInfoFlow::getId, dto.getId()));
                customerContactService.saveBatch(dto.getContactsList().stream().map(item -> {
                    CustomerContact customerContact = new CustomerContact();
                    BeanUtils.copyProperties(item, customerContact);
                    customerContact.setId(null);
                    customerContact.setCustomer_id(dto.getCustomer_id());
                    return customerContact;
                }).collect(Collectors.toList()));
                customerPutStorageService.saveBatch(dto.getPutStorageList().stream().map(item -> {
                    CustomerPutStorage customerPutStorage = new CustomerPutStorage();
                    BeanUtils.copyProperties(item, customerPutStorage);
                    customerPutStorage.setId(null);
                    customerPutStorage.setCustomer_id(dto.getCustomer_id());
                    return customerPutStorage;
                }).collect(Collectors.toList()));
                customerFollowService.saveBatch(dto.getFollows(), dto.getCustomer_id());
                return f;
            } else {
                return customerFollowService.saveBatch(dto.getFollows(), dto.getCustomer_id());
            }
        } else if (flowResult == 1) {
            return true;
        } else {
            throw new CommonException("审核失败");
        }
    }

    @Override
    public Page<CustomerFlowVO> page(Integer current_page, Integer page_size, String name, Long industry_id, Boolean is_my_customer_page) {
        Page<CustomerFlowVO> page = new Page<CustomerFlowVO>(current_page, page_size);
        Long userId = ThreadLocalUserUtil.get().getId();
        List<Long> userIds = new ArrayList<>();
        userIds.add(userId);
        if (!is_my_customer_page) {
            List<Long> dept = userService.getUserResponsibleDeptIdByBusinessHead(userId);
            if (dept.size() != 0) {
                for (int i = 0; i < dept.size(); i++) {
                    List<User> users = userService.getUserByDeptId(dept.get(i));
                    if (users != null && users.size() > 0) users.forEach(item -> userIds.add(item.getId()));
                }
            }
        }
        List<CustomerFlowVO> list = baseMapper.page(page, name, industry_id, userIds);
        for (CustomerFlowVO vo : list) {
            CustomerInfoFlow flow = new CustomerInfoFlow();
            BeanUtils.copyProperties(vo, flow);
            vo.setCheck(WorkFlowUtil.canCheckData(userId, flow));
        }
        page.setRecords(list);
        return page;
    }

    @Override
    public CustomerInfoFlowDTO getOneDtoById(Long id) {
        CustomerInfoFlowDTO dto = baseMapper.getOneDtoById(id);
        CustomerInfoFlow flow = new CustomerInfoFlow();
        BeanUtils.copyProperties(dto, flow);
        Long userId = ThreadLocalUserUtil.get().getId();
        if (flow.getFlow_status() == null) {
            dto.setWhether_check(false);
        } else {
            boolean b = WorkFlowUtil.canCheckData(userId, flow);
            dto.setWhether_check(b);
        }
        Long user_id = ThreadLocalUserUtil.get().getId();
        int level = dataQueryBusinessLevelService.getUserMaxLevel("customer_contact", user_id);
        List<CustomerContactTmp> contactTmpList = customerContactTmpService.list(Wrappers.<CustomerContactTmp>lambdaQuery().eq(CustomerContactTmp::getCustomer_info_flow_id, dto.getId()));
        if (CollectionUtils.isNotEmpty(contactTmpList)) {
            contactTmpList.forEach(customerContactTmp -> {
                if (level != -1 && level <= customerContactTmp.getLevel_num()) {
                    customerContactTmp.setCan_look(true);
                }
            });
        }
        List<CustomerPutStorageTmp> customerPutStorageTmpList = customerPutStorageTmpService.list(Wrappers.<CustomerPutStorageTmp>lambdaQuery().eq(CustomerPutStorageTmp::getCustomer_info_flow_id, dto.getId()));
        dto.setPutStorageList(customerPutStorageTmpList);
        dto.setContactsList(contactTmpList);
        return dto;
    }

    @Override
    public Long draftsIsNull() {
        Long userId = ThreadLocalUserUtil.get().getId();
        CustomerInfoFlow one = this.getOne(Wrappers.<CustomerInfoFlow>lambdaQuery().eq(CustomerInfoFlow::getFlow_applyer_id, userId).eq(CustomerInfoFlow::getFlow_status, 0));
        if (one != null) {
            return one.getId();
        } else {
            return -1L;
        }
    }

    @Override
    public List<CustomerChangeVO> equalsData(CustomerInfoFlowDTO dto) {
        List<CustomerChangeVO> list = new ArrayList<>();
        if (dto.getCustomer_id() == null) {
            return list;
        } else {
            CustomerInfoDTO customerInfo = customerInfoService.getOneDtoById(dto.getCustomer_id());
            if (customerInfo == null) {
                return list;
            } else {
                CustomerInfo oldData = new CustomerInfo();
                CustomerInfo newData = new CustomerInfo();
                BeanUtils.copyProperties(dto, newData);
                BeanUtils.copyProperties(customerInfo, oldData);
                Collections.sort(dto.getFunnels());
                Collections.sort(dto.getSelection_reasons());
                Collections.sort(customerInfo.getFunnels());
                Collections.sort(customerInfo.getSelection_reasons());
                this.equalsData(oldData, newData, list);//比较基本数据
                if (!dto.getFunnels().equals(customerInfo.getFunnels())) {//比较销售漏斗
                    list.add(new CustomerChangeVO("销售漏斗", dictionaryService.getDictNames(customerInfo.getFunnels()), dictionaryService.getDictNames(dto.getFunnels())));
                }
                if (!dto.getSelection_reasons().equals(customerInfo.getSelection_reasons())) {//比较选择原因
                    list.add(new CustomerChangeVO("选择原因", dictionaryService.getDictNames(customerInfo.getSelection_reasons()), dictionaryService.getDictNames(dto.getSelection_reasons())));
                }
                if (dto.getPut_storage_modify() != null && dto.getPut_storage_modify().equals(1)) {
                    list.add(new CustomerChangeVO("入库信息", "", ""));
                }
                if (dto.getContact_modify() != null && dto.getContact_modify().equals(1)) {
                    list.add(new CustomerChangeVO("联系人信息", "", ""));
                }
                return list;
            }
        }
    }

    /**
     * 比较数据并加入不一致的前后数据
     *
     * @param old
     * @param info
     * @param list
     */
    private void equalsData(CustomerInfo old, CustomerInfo info, List<CustomerChangeVO> list) {
        if (old == info) return;
        if (!Objects.equals(old.getName(), info.getName())) {
            list.add(new CustomerChangeVO("客户名称", old.getName(), info.getName()));
        }
        if (!Objects.equals(old.getAddress(), info.getAddress())) {
            list.add(new CustomerChangeVO("客户地址", old.getAddress(), info.getAddress()));
        }
        if (!Objects.equals(old.getBrand(), info.getBrand())) {
            list.add(new CustomerChangeVO("客户品牌", old.getBrand(), info.getBrand()));
        }
        if (!Objects.equals(old.getIndustry_id(), info.getIndustry_id())) {
            Dictionary oldIndustry = dictionaryService.getById(old.getIndustry_id());
            Dictionary newIndustry = dictionaryService.getById(info.getIndustry_id());
            list.add(new CustomerChangeVO("客户行业", oldIndustry == null ? null : oldIndustry.getName(), newIndustry == null ? null : newIndustry.getName()));//等待修改
        }
        if (!Objects.equals(old.getBudget(), info.getBudget())) {
            list.add(new CustomerChangeVO("客户预算", old.getBudget() == null ? null : old.getBudget().toString(), info.getBudget() == null ? null : info.getBudget().toString()));
        }
        if (!Objects.equals(old.getMaintenance_staff_id(), info.getMaintenance_staff_id())) {
            User oldUser = userService.getById(old.getMaintenance_staff_id());
            User newUser = userService.getById(info.getMaintenance_staff_id());
            list.add(new CustomerChangeVO("维护人员", oldUser == null ? null : oldUser.getName(), newUser == null ? null : newUser.getName()));
        }
        if (!Objects.equals(old.getPerson_in_charge_id(), info.getPerson_in_charge_id())) {
            User oldUser = userService.getById(old.getPerson_in_charge_id());
            User newUser = userService.getById(info.getPerson_in_charge_id());
            list.add(new CustomerChangeVO("客户负责人", oldUser == null ? null : oldUser.getName(), newUser == null ? null : newUser.getName()));
        }
        if (!Objects.equals(old.getPerson_in_charge_name(), info.getPerson_in_charge_name())) {
            list.add(new CustomerChangeVO("总负责人", old.getPerson_in_charge_name(), info.getPerson_in_charge_name()));
        }
        if (!Objects.equals(old.getPerson_in_charge_phone(), info.getPerson_in_charge_phone())) {
            list.add(new CustomerChangeVO("总负责人联系方式", old.getPerson_in_charge_phone(), info.getPerson_in_charge_phone()));
        }
        if (!Objects.equals(old.getPerson_in_charge_dept(), info.getPerson_in_charge_dept())) {
            list.add(new CustomerChangeVO("总负责人部门", old.getPerson_in_charge_dept(), info.getPerson_in_charge_dept()));
        }
        if (!Objects.equals(old.getPerson_in_charge_post(), info.getPerson_in_charge_post())) {
            list.add(new CustomerChangeVO("总负责人职务", old.getPerson_in_charge_post(), info.getPerson_in_charge_post()));
        }
        if (!Objects.equals(old.getDirect_responsible_person_name(), info.getDirect_responsible_person_name())) {
            list.add(new CustomerChangeVO("直接负责人", old.getDirect_responsible_person_name(), info.getDirect_responsible_person_name()));
        }
        if (!Objects.equals(old.getDirect_responsible_person_phone(), info.getDirect_responsible_person_phone())) {
            list.add(new CustomerChangeVO("直接负责人联系方式", old.getDirect_responsible_person_phone(), info.getDirect_responsible_person_phone()));
        }
        if (!Objects.equals(old.getDirect_responsible_person_dept(), info.getDirect_responsible_person_dept())) {
            list.add(new CustomerChangeVO("直接负责人部门", old.getDirect_responsible_person_dept(), info.getDirect_responsible_person_dept()));
        }
        if (!Objects.equals(old.getDirect_responsible_person_post(), info.getDirect_responsible_person_post())) {
            list.add(new CustomerChangeVO("直接负责人职务", old.getDirect_responsible_person_post(), info.getDirect_responsible_person_post()));
        }
        if (!Objects.equals(old.getClerk_name(), info.getClerk_name())) {
            list.add(new CustomerChangeVO("办事员", old.getClerk_name(), info.getClerk_name()));
        }
        if (!Objects.equals(old.getClerk_phone(), info.getClerk_phone())) {
            list.add(new CustomerChangeVO("办事员联系方式", old.getClerk_phone(), info.getClerk_phone()));
        }
        if (!Objects.equals(old.getCompany_structure_analysis(), info.getCompany_structure_analysis())) {
            list.add(new CustomerChangeVO("公司权利架构分析", old.getCompany_structure_analysis(), info.getCompany_structure_analysis()));
        }
        if (!Objects.equals(old.getCompany_launch_background(), info.getCompany_launch_background())) {
            list.add(new CustomerChangeVO("投放背景分析", old.getCompany_launch_background(), info.getCompany_launch_background()));
        }
        if (!Objects.equals(old.getCompany_information(), info.getCompany_information())) {
            list.add(new CustomerChangeVO("客户信息", old.getCompany_information(), info.getCompany_information()));
        }
        if (!Objects.equals(old.getCompany_programme(), info.getCompany_programme())) {
            list.add(new CustomerChangeVO("客户方案", old.getCompany_programme(), info.getCompany_programme()));
        }
        if (!Objects.equals(old.getGroup(), info.getGroup())) {
            Dictionary oldIndustry = dictionaryService.getById(old.getGroup());
            Dictionary newIndustry = dictionaryService.getById(info.getGroup());
            list.add(new CustomerChangeVO("所属集团", oldIndustry != null ? oldIndustry.getName() : "未填写", newIndustry != null ? newIndustry.getName() : "未填写"));
        }
    }

    @Override
    public Integer getFlowCheckCount(Boolean is_my_customer_page) {
        Long id = ThreadLocalUserUtil.get().getId();
        if (is_my_customer_page) {
            return this.count(Wrappers.<CustomerInfoFlow>lambdaQuery().eq(CustomerInfoFlow::getFlow_applyer_id, id).eq(CustomerInfoFlow::getFlow_status, 3).isNull(CustomerInfoFlow::getDeleted_at));
        } else {
            int count = 0;
            List<CustomerInfoFlow> list = this.list(Wrappers.<CustomerInfoFlow>lambdaQuery().eq(CustomerInfoFlow::getFlow_status, 3).isNull(CustomerInfoFlow::getDeleted_at));
            for (CustomerInfoFlow flow : list) {
                boolean b = WorkFlowUtil.canCheckData(id, flow);
                if (b) {
                    count++;
                }
            }
            return count;
        }
    }

    @Override
    public Boolean getFlowIsEnd(Long id) {
        CustomerInfoFlow flow = this.getById(id);
        Long userId = ThreadLocalUserUtil.get().getId();
        Long curCheckIndex = WorkFlowUtil.getCurCheckIndex(flow.getFlow_json(), flow.getFlow_current_node_id());
        int i = new WorkFlowUtil<CustomerInfoFlow, CustomerInfoFlowMapper>(flow.getId(), userId, CustomerInfoFlow.class).NextIsEnd(new WorkFlowCheckDTO(flow.getFlow_current_node_id(), curCheckIndex));
        return i == 1;
    }


    @Override
    @Transactional
    public Boolean remove(Long flow_id, Long wfData_id) {
        Long userId = ThreadLocalUserUtil.get().getId();
        return new WorkFlowUtil<CustomerInfoFlow, CustomerInfoFlowMapper>(flow_id, userId, CustomerInfoFlow.class).Delete(wfData_id) == 1;
    }

    @Override
    public Boolean actualDelete(Long flow_id, Long wfData_id) {
        Long userId = ThreadLocalUserUtil.get().getId();
        return new WorkFlowUtil<CustomerInfoFlow, CustomerInfoFlowMapper>(flow_id, userId, CustomerInfoFlow.class).ActualDelete(wfData_id) == 1;
    }

    @Override
    public List<String> getHistoryUser(Long customer_id) {
        return customerFollowService.getHistoryUser(customer_id);
    }

    @Override
    public CustomerInfoFlowDTO getFlowDtoById(Long id) {
        CustomerInfoFlowDTO dto = baseMapper.queryDto(id);
        dto.setFunnels(customerFunnelTmpService.list(Wrappers.<CustomerFunnelTmp>lambdaQuery().eq(CustomerFunnelTmp::getCustomer_info_flow_id, dto.getId())).stream().map(CustomerFunnelTmp::getFunnel_type_id).collect(Collectors.toList()));
        dto.setSelection_reasons(customerSelectionReasonTmpService.list(Wrappers.<CustomerSelectionReasonTmp>lambdaQuery().eq(CustomerSelectionReasonTmp::getCustomer_info_flow_id, dto.getId())).stream().map(CustomerSelectionReasonTmp::getSelection_reason_id).collect(Collectors.toList()));
        dto.setPutStorageList(customerPutStorageTmpService.list(Wrappers.<CustomerPutStorageTmp>lambdaQuery().eq(CustomerPutStorageTmp::getCustomer_info_flow_id, dto.getId())));
        dto.setContactsList(customerContactTmpService.list(Wrappers.<CustomerContactTmp>lambdaQuery().eq(CustomerContactTmp::getCustomer_info_flow_id, dto.getId())));
        // 查出客户的跟进记录
        List<CustomerFollowTmp> list = customerFollowTmpService.list(Wrappers.<CustomerFollowTmp>lambdaQuery().isNull(CustomerFollowTmp::getDeleted_at).eq(CustomerFollowTmp::getCustomer_info_flow_id, dto.getId()));
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> ids = list.stream().map(CustomerFollowTmp::getId).collect(Collectors.toList());
            Map<Long, List<CustomerFollowAdvanceTmp>> customerFollowAdvanceTmpMap = customerFollowAdvanceTmpService.list(Wrappers.<CustomerFollowAdvanceTmp>lambdaQuery().in(CustomerFollowAdvanceTmp::getCustomer_follow_tmp_id, ids)).stream().collect(Collectors.groupingBy(CustomerFollowAdvanceTmp::getCustomer_follow_tmp_id));
            Map<Long, List<CustomerRecommendedResourcesTmp>> customerRecommendedResourcesTmpMap = customerRecommendedResourcesTmpService.list(Wrappers.<CustomerRecommendedResourcesTmp>lambdaQuery().in(CustomerRecommendedResourcesTmp::getCustomer_follow_tmp_id, ids)).stream().collect(Collectors.groupingBy(CustomerRecommendedResourcesTmp::getCustomer_follow_tmp_id));
            Map<Long, List<CustomerFollowPhotoTmp>> customerFollowPhotoTmpMap = customerFollowPhotoTmpService.list(Wrappers.<CustomerFollowPhotoTmp>lambdaQuery().in(CustomerFollowPhotoTmp::getCustomer_follow_tmp_id, ids)).stream().collect(Collectors.groupingBy(CustomerFollowPhotoTmp::getCustomer_follow_tmp_id));
            dto.setFollows(list.stream().map(item -> {
                CustomerFollowTmpDTO customerFollowTmpDTO = new CustomerFollowTmpDTO();
                BeanUtils.copyProperties(item, customerFollowTmpDTO);
                customerFollowTmpDTO.setUrl_list(customerFollowPhotoTmpMap.getOrDefault(item.getId(), new ArrayList<>()).stream().map(CustomerFollowPhotoTmp::getUrl).collect(Collectors.toList()));
                customerFollowTmpDTO.setAction_list(customerFollowAdvanceTmpMap.getOrDefault(item.getId(), new ArrayList<>()).stream().map(CustomerFollowAdvanceTmp::getAdvance_id).collect(Collectors.toList()));
                customerFollowTmpDTO.setResource_list(customerRecommendedResourcesTmpMap.getOrDefault(item.getId(), new ArrayList<>()).stream().map(CustomerRecommendedResourcesTmp::getResources_id).collect(Collectors.toList()));
                return customerFollowTmpDTO;
            }).collect(Collectors.toList()));
        } else {
            dto.setFollows(new ArrayList<>());
        }
        Long user_id = ThreadLocalUserUtil.get().getId();
        dto.setCan_check(WorkFlowUtil.canCheckData(user_id, dto));
        return dto;
    }
}
